/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sapra.abc;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import nextapp.echo2.app.Alignment;
import nextapp.echo2.app.Button;
import nextapp.echo2.app.CheckBox;
import nextapp.echo2.app.Color;
import nextapp.echo2.app.Column;
import nextapp.echo2.app.ContentPane;
import nextapp.echo2.app.Extent;
import nextapp.echo2.app.Grid;
import nextapp.echo2.app.Insets;
import nextapp.echo2.app.Label;
import nextapp.echo2.app.Row;
import nextapp.echo2.app.SelectField;
import nextapp.echo2.app.Table;
import nextapp.echo2.app.TextField;
import nextapp.echo2.app.event.ActionEvent;
import nextapp.echo2.app.event.ActionListener;
import nextapp.echo2.app.list.DefaultListModel;
import nextapp.echo2.app.table.DefaultTableModel;
import org.sapra.core.DBManager;
import org.sapra.dao.Departamento;
import org.sapra.dao.Empresa;
import org.sapra.dao.Polizaseguro;
import org.sapra.dao.Practicante;
import org.sapra.eai.aig.aig;
import org.sapra.echo.Helpers;
import org.sapra.echo.wAviso;
import org.sapra.logon.dLogin;
import org.sapra.main.vPrincipal;

/**
 *
 * @author luiz
 */
public class vCambioEmpresa extends ContentPane{
    
    private vPrincipal princ;
    private CheckBox  paterno, materno, nombre;
    private Label emp, emp2, ap_p, ap_ma,nom,conv;
    private TextField nom_empresa, nom_practicante, ap_pat, ap_mat,con, ap_pat2, ap_mat2,nom_pract, fec1,fec2,fec3;
    private SelectField nom_emp_des, nom_emp_des2;
    private Button cambiar,buscar, convenio, buscar2, cancelar,ingresar;
    private Table tab_pract;
    private Empresa empr;
    private Practicante pract, pract2;
    private Column mParent;
    private Row row1, row2, row3, row4,rowb,rowc,rowc1;
    private Grid ac1,ac2, ac3;
    public final static int CONVENIO = 2;
    public final static int BUSCAR = 1;
    public final static int BUSQUEDA=3;
    public static int accion;
    private String title[]={"CONVENIO", "PATERNO", "MATERNO", "NOMBRE", "EMPRESA", "FECHA DE INICIO", "FECHA DE TERMINO", "FECHA DE CANCELACION", "ESTATUS"};
    private List<Practicante> lista_pract=null;
    private int led1=0,led2=0,led3=0;

    public vCambioEmpresa(vPrincipal princ){
            this.princ=princ;
            initComponents();

    }

    public void initComponents(){

        Column col1;
        if(mParent != null) col1 = mParent;
        else{
            col1 = Helpers.Column("Default", new Extent(5),this);
            Row x=princ.getMenu();
            x.setAlignment(Alignment.ALIGN_CENTER);
            col1.add(x);
        }

        //ENCABEZADO
        Row rowh=Helpers.Row("default", new Extent(5), col1);
        Helpers.Label("CAMBIAR DE EMPRESA A UN PRACTICANTE.", new Color(0x011dac), rowh);
        rowh.setAlignment(Alignment.ALIGN_CENTER);

        Row rowh2=Helpers.Row("default", new Extent(5), col1);
        convenio=Helpers.Button("CONVENIO", rowh2, new ActionListener(){public void actionPerformed(ActionEvent e) {buscarConvenio(e);}});
        buscar2=Helpers.Button("BUSCAR PRACTICANTE", rowh2, new ActionListener(){public void actionPerformed(ActionEvent e) {buscarPracticante(e);}});
        rowh2.setAlignment(Alignment.ALIGN_CENTER);

        //DATOS DEL PRACTICANTE A CAMBIAR
        row1=Helpers.Row("DEFAULT", new Extent(5), col1);
        ac1=new Grid(2);
        paterno=Helpers.CheckBox("APELLIDO PATERNO", ac1);
        ap_pat2=Helpers.Text("", ac1);
        materno=Helpers.CheckBox("APELLIDO MATERNO", ac1);
        ap_mat2=Helpers.Text("", ac1);
        nombre=Helpers.CheckBox("NOMBRES", ac1);
        nom_pract=Helpers.Text("", ac1);
        ac1.setInsets(new Insets(new Extent(5)));
        row1.add(ac1);
        row1.setAlignment(Alignment.ALIGN_CENTER);

        rowb=Helpers.Row("DEFAULT", new Extent(5), col1);
        buscar=Helpers.Button("BUSCAR", rowb, new ActionListener(){public void actionPerformed(ActionEvent e) {busquedaPracticante(e);}});
        cancelar=Helpers.Button("CANCELAR", rowb, new ActionListener(){public void actionPerformed(ActionEvent e) {menuCancelar(e);}});
        rowb.setAlignment(Alignment.ALIGN_CENTER);


        //DATOS DEL CONVENIO
        rowc=Helpers.Row("DEFAULT", new Extent(5), col1);
        conv=Helpers.Label("No. CONVENIO:", Color.BLACK, rowc);
        con=Helpers.Text("", rowc);
        ingresar=Helpers.Button("INGRESAR", rowc, new ActionListener(){public void actionPerformed(ActionEvent e) {establecerPracticante(e);}});
        rowc.setAlignment(Alignment.ALIGN_CENTER);


        //DATOS DE LA EMPRESA ACTUAL Y LA EMPRESA DESTINO
        row2=Helpers.Row("DEFAULT", new Extent(5), col1);
        ac2=new Grid(2);
        nom=Helpers.Label("NOMBRE:", Color.BLACK, ac2);
        nom_practicante=Helpers.Text("", ac2);
        ap_p=Helpers.Label("APELLIDO PATERNO:", Color.BLACK, ac2);
        ap_pat=Helpers.Text("", ac2);
        ap_ma=Helpers.Label("APELLIDO MATERNO:", Color.BLACK, ac2);
        ap_mat=Helpers.Text("", ac2);
        Helpers.Label("FECHA DE INICIO:", Color.BLACK, ac2);
        fec1=Helpers.Text("", ac2);
        Helpers.Label("FECHA DE TERMINO:", Color.BLACK, ac2);
        fec2=Helpers.Text("", ac2);
        Helpers.Label("FECHA DE CANCELACION:", Color.BLACK, ac2);
        fec3=Helpers.Text("", ac2);
        emp=Helpers.Label("EMPRESA ACTUAL:", Color.BLACK, ac2);
        nom_empresa=Helpers.Text("", ac2);
        nom_empresa.setWidth(new Extent(500));
        emp2=Helpers.Label("EMPRESA DESTINO:", Color.BLACK, ac2);
        nom_emp_des=Helpers.SelectField(ac2, null);
        nom_emp_des.setWidth(new Extent(500));
        ac2.setWidth(new Extent(700));
        ac1.setInsets(new Insets(new Extent(7)));
        row2.add(ac2);
        row2.setAlignment(Alignment.ALIGN_CENTER);

        //BOTON DE COMANDO
        row3=Helpers.Row("DEFAULT", new Extent(5), col1);
        cambiar=Helpers.Button("CAMBIAR", row3, new ActionListener(){public void actionPerformed(ActionEvent e) {menuCambiar(e);}});
        cancelar=Helpers.Button("CANCELAR", row3, new ActionListener(){public void actionPerformed(ActionEvent e) {menuCancelar(e);}});
        row3.setAlignment(Alignment.ALIGN_CENTER);

        rowc1=Helpers.Row("DEFAULT", new Extent(5), col1);
        Helpers.Label("EMPRESA DESTINO", Color.BLACK, rowc1);
        nom_emp_des2=Helpers.SelectField(rowc1, null);
        nom_emp_des2.setWidth(new Extent(500));
        cambiar=Helpers.Button("CAMBIAR", rowc1, new ActionListener(){public void actionPerformed(ActionEvent e) {menuCambiarTabla(e);}});
        rowc1.setAlignment(Alignment.ALIGN_CENTER);

        //TABLA DE PRACTICANTES DE LA EMPRESA ACTUAL
        row4=Helpers.Row("DEFAULT", new Extent(5), col1);
        tab_pract=Helpers.Tabla();
        row4.add(tab_pract);
        cancelar=Helpers.Button("CANCELAR", row4, new ActionListener(){public void actionPerformed(ActionEvent e) {menuCancelar(e);}});
        row4.setAlignment(Alignment.ALIGN_CENTER);

        row1.setEnabled(false);
        row1.setVisible(false);
        rowc.setEnabled(false);
        rowc.setVisible(false);
        rowc1.setEnabled(false);
        rowc1.setVisible(false);
        row2.setEnabled(false);
        row2.setVisible(false);
        row3.setEnabled(false);
        row3.setVisible(false);
        row4.setEnabled(false);
        row4.setVisible(false);
        rowb.setEnabled(false);
        rowb.setVisible(false);

        establecerChecBox();
        FirstTime();

    }

       void FirstTime(){

        UpdateView();

       }

     void UpdateView(){
        List<Empresa> emps= dEmpresa.getEmpresas(dLogin.getEmpresa().getFk_corporativoId());
        nom_emp_des.setModel(new DefaultListModel(emps.toArray()));
        nom_emp_des2.setModel(new DefaultListModel(emps.toArray()));
        nom_empresa.setText(dLogin.getEmpresa().getRazon_empresa());
        DefaultTableModel dtm=new DefaultTableModel(9,0);
        for(int i=0;i<title.length;i++){
                dtm.setColumnName(i,title[i]);
            }
        tab_pract.setModel(dtm);

        ap_pat2.setEnabled(false);
        ap_mat2.setEnabled(false);
        nom_pract.setEnabled(false);

       }

     public void establecerChecBox(){
           paterno.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(paterno.isSelected()){
                    led2=100;
                    ap_pat2.setEnabled(true);

                }else{
                     ap_pat2.setEnabled(false);
                     led2=0;
                }
            }
        });
        materno.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(materno.isSelected()){
                    led3=1000;
                    ap_mat2.setEnabled(true);
                }else{
                    ap_mat2.setEnabled(false);
                    led3=0;
                }
            }
        });
       nombre.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    if(nombre.isSelected()){
                        nom_pract.setEnabled(true);
                        led1=10;
                    }else{
                        nom_pract.setEnabled(false);
                        led1=0;
                    }
                }
            });
         
     }

     public void buscarConvenio(ActionEvent e){
         rowc.setEnabled(true);
         rowc.setVisible(true);
         row2.setEnabled(true);
         row2.setVisible(true);
         row3.setEnabled(true);
         row3.setVisible(true);
         ocultarFilas();
         accion=CONVENIO;


     }

     public void buscarPracticante(ActionEvent e){
         row1.setEnabled(true);
         row1.setVisible(true);
         rowb.setEnabled(true);
         rowb.setVisible(true);
         rowc1.setEnabled(true);
         rowc1.setVisible(true);
         ocultarFilas();
         accion=BUSCAR;

     }

     void menuCancelar(ActionEvent e){
            ocultarFilas();
            CleanFields();
        }

       

        public void ocultarFilas(){
                        if(accion==CONVENIO){
         rowc.setEnabled(false);
         rowc.setVisible(false);
         row2.setEnabled(false);
         row2.setVisible(false);
         row3.setEnabled(false);
         row3.setVisible(false);
            }
            if(accion==BUSCAR){
         row1.setEnabled(false);
         row1.setVisible(false);
         rowb.setEnabled(false);
         rowb.setVisible(false);
        rowc1.setEnabled(false);
        rowc1.setVisible(false);
            }
            if(accion==BUSQUEDA){
        row4.setEnabled(false);
        row4.setVisible(false);

            }
        }

      public void establecerPracticante(ActionEvent e){
          try{
              int x=Integer.parseInt(con.getText().trim());
          }catch (Exception ex) {
                add(new wAviso("ERROR","FORMATO ERRONEO PARA EL CONVENIO"));
            }
          pract=new Practicante();
          Empresa em=new Empresa();
          Departamento dep=new Departamento();
          try{
          pract=dPracticante.getPracticante(Integer.parseInt(con.getText()));}catch (Exception ex) {
                add(new wAviso("ERROR","FORMATO ERRONEO PARA EL CONVENIO"));
            }
          dep=dDepartamento.getDepartamento(pract.getFk_departamentoId());
          em=dEmpresa.SelEmp(dep.getFk_empresaId());

          if(pract==null){
              add(new wAviso("ERROR","ERROR INTERNO"));
          }
          if(dep==null){
              add(new wAviso("ERROR","ERROR INTERNO"));
          }
          if(em==null){
              add(new wAviso("ERROR","PRACTICANTE NO ENCONTRADO, ESTATUS BAJA O CONVENIO NO EXISTE"));
          }
          else{
              nom_practicante.setText(pract.getNombre());
              ap_pat.setText(pract.getPaterno());
              ap_mat.setText(pract.getMaterno());
              nom_empresa.setText(em.getRazon_empresa());
              fec1.setText(pract.getFec_inicioContrato().toString());
              fec2.setText(pract.getFec_terminoContrato().toString());
              if(pract.getFec_cancelacion()==null||pract.getFec_cancelacion().equals(""))
              {
                  fec3.setText("N/D");
              }
          else{
              fec3.setText(pract.getFec_cancelacion().toString());}
          }
      }

      public void busquedaPracticante(ActionEvent e){
         row4.setEnabled(true);
         row4.setVisible(true);
         accion=BUSQUEDA;
         //int sumaLed=led1+led2+led3;//suma 1110;
         int sumaLed=0;
          String cad="";
                    if(led1==10){
                        sumaLed+=led1;
                        if(nom_pract.getText().trim().equals("")){
                            add(new wAviso("ERROR","FAVOR DE ESCRIBIR EL NOMBRE"));
                                    return;
                        }

                    }
                    if(led2==100){
                        sumaLed+=led2;
                        if(ap_pat2.getText().trim().equals("")){
                            add(new wAviso("ERROR","FAVOR DE ESCRIBIR EL APELLIDO PATERNO"));
                                    return;
                        }

                    }
                    if(led3==1000){
                        sumaLed+=led3;
                        if(ap_mat2.getText().trim().equals("")){
                            add(new wAviso("ERROR","FAVOR DE ESCRIBIR EL APELLIDO MATERNO"));
                                    return;
                        }

                    }
                     System.out.println(sumaLed);
                    if(sumaLed != 0){
                        if(sumaLed == 1110){//las 3
                            lista_pract=busqueda(nom_pract.getText().trim(),ap_pat2.getText().trim(),ap_mat.getText().trim());
                        }
                        if(sumaLed == 1100){ // led 2 y 3
                            lista_pract=busqueda(null,ap_pat.getText().trim(),ap_mat.getText().trim());
                        }
                        if(sumaLed == 1010){//led 1 y 3
                            lista_pract=busqueda(nom_pract.getText().trim(),null,ap_mat2.getText().trim());
                        }
                        if(sumaLed ==110){ //led1 y 2
                            lista_pract=busqueda(nom_pract.getText().trim(),ap_pat2.getText().trim(),null);
                        }
                        if(sumaLed == 1000){//led 3
                            lista_pract=busqueda(null,null,ap_mat2.getText().trim());
                        }
                        if(sumaLed == 100){//led2
                           lista_pract=busqueda(null,ap_pat2.getText().trim(),null);
                        }
                        if(sumaLed == 10){//led1
                            lista_pract=busqueda(nom_pract.getText().trim(),null,null);
                        }
                        if(lista_pract !=null )
                            tab_pract.setModel(modeloTabla());
                        else{
                            add(new wAviso("ERROR","NO EXISTEN PRACTICANTES CON ESA DESCRIPCION"));
                                    return;
                        }

                    }

                }

      //}

      public void CleanFields(){
          ap_pat.setText("");
          ap_mat.setText("");
          nom_practicante.setText("");
          ap_pat2.setText("");
          ap_mat2.setText("");
          nom_pract.setText("");
          nom_empresa.setText("");
          con.setText("");
          fec1.setText("");
          fec2.setText("");
          fec3.setText("");


        }

      static List<Practicante> busqueda(String txt1,String txt2,String txt3){
        List<Practicante> resp = null;
        String sql = "SELECT p.practicanteId,p.nombre,p.paterno,p.materno,"
                + " p.fec_inicioContrato,p.status,p.fec_terminoContrato,e.razon_empresa"
                + " FROM practicante p "
                + " INNER JOIN departamento d"
                + " ON d.departamentoId=p.fk_departamentoId"
                + " INNER JOIN empresa e"
                + " ON d.fk_empresaId=e.empresaId "
                + " WHERE ";
                if(txt1 != null){
                    sql+=" ( p.nombre LIKE '"+txt1+"%' OR p.nombre LIKE '%"+txt1+"%' OR p.nombre LIKE '%"+txt1+"')";
                    if(txt2 != null || txt3 !=null)
                        sql += " AND ";
                }

                if(txt2 != null){
                    sql+=" ( p.paterno LIKE '"+txt2+"%' OR p.paterno LIKE '%"+txt2+"%' OR p.paterno LIKE '%"+txt2+"')";
                    if( txt3 !=null)
                        sql += " AND ";
                }

                if(txt3 != null){
                    sql+=" ( p.materno LIKE '"+txt3+"%' OR p.materno LIKE '%"+txt3+"%' OR p.materno LIKE '%"+txt3+"')";
                }

                sql+=" ORDER BY e.razon_empresa,p.nombre ASC";
        try {
            resp = DBManager.getQuery(Practicante.class,sql);
        } catch (Exception e) {
            Logger.getLogger(dPracticante.class.getName()).log(Level.SEVERE, null, e);
            return null;
        }
        return resp;
    }

    public DefaultTableModel modeloTabla(){
            SimpleDateFormat spd=new SimpleDateFormat("yyyy-MM-dd");
            DefaultTableModel dtm=new DefaultTableModel(9,0);
            for(int i=0;i<title.length;i++){
                    dtm.setColumnName(i,title[i]);
                }
            for(int i=0;i<lista_pract.size();i++){
                    Practicante p=(Practicante)lista_pract.get(i);
                    Object[] obj=new Object[9];
                    obj[0]=p.getPracticanteId()+"";
                    obj[1]=p.getPaterno();
                    obj[2]=p.getMaterno();
                    obj[3]=p.getNombre();
                    obj[4]=p.getRazon_empresa();
                    obj[5]=p.getFec_inicioContrato()+"";
                    if(p.getFec_terminoContrato()==null || p.getFec_terminoContrato().equals(""))
                        obj[6]="N/D";
                    else
                        obj[6]=spd.format(p.getFec_terminoContrato());
                     if(p.getFec_cancelacion()==null || p.getFec_cancelacion().equals(""))
                        obj[7]="N/D";
                    else
                        obj[7]=spd.format(p.getFec_cancelacion());
                    obj[8]=p.getStatus();
                    dtm.addRow(obj);
            }
            return dtm;
    }

     public void  menuCambiar(ActionEvent e){
       if(pract==null){
           add(new wAviso("ERROR","DEBE INTRODUCIR EL NUMERO DE CONVENIO."));
       }
 else{
       Empresa emp=new Empresa();
       List<Empresa> emps= dEmpresa.getEmpresas(dLogin.getEmpresa().getFk_corporativoId());
       emp=(Empresa)nom_emp_des.getSelectedItem();
       Departamento dep=new Departamento();
       dep=dDepartamento.getDepartamento2(emp.getEmpresaId());
       //dep.setFk_empresaId(emp.getEmpresaId());
       pract.setFk_departamentoId(dep.getDepartamentoId());
       int res=dPracticante.SaveUpdate(pract);
       Polizaseguro ps=new Polizaseguro(pract.getPracticanteId());
       ps=new Polizaseguro(pract.getPracticanteId(),ps.getFk_planseguroId());
       aig po=new aig();
       try{
           po.xmlEditar(ps);
       }
       catch(Exception exc){
           add(new wAviso("ERROR","NO SE PUDO CREAR LA POLIZA"));
       }
       if(res!=0){
           add(new wAviso("EXITO","EL PRACTICANTE"+""+pract.getNombre()+""+"HA SIDO CAMBIADO A LA EMPRESA"+""+emp.getRazon_empresa()+""+"EXITOSAMENTE"));
       }
 else{
        add(new wAviso("ERROR","EL PRACTICANTE NO PUDO SER CAMBIADO"));
 }
       CleanFields();
       UpdateView();}
         
     }

     public void  menuCambiarTabla(ActionEvent e){
         Empresa emp1=new Empresa();
         Departamento dep=new Departamento();
         pract2=new Practicante();
         Practicante prc=new Practicante();
         int sel=0;

         //OBTENER AL PRACTICANTE Y EZTABLECER DATO
         sel=tab_pract.getSelectionModel().getMinSelectedIndex();
         pract2=lista_pract.get(sel);
         if(pract2==null){
             add(new wAviso("ERROR","DEBE BUSCAR AL PRACTICANTE ANTES DE CONTINUAR"));
         }
 else{
         /*Empresa emp1=new Empresa();
         Departamento dep=new Departamento();
         pract2=new Practicante();
         Practicante prc=new Practicante();
         int sel=0;*/

         //OBTENER AL PRACTICANTE Y EZTABLECER DATO
         sel=tab_pract.getSelectionModel().getMinSelectedIndex();
         pract2=lista_pract.get(sel);
         prc=dPracticante.getPracticante(pract2.getPracticanteId());
         emp1=(Empresa)nom_emp_des2.getSelectedItem();
         dep=dDepartamento.getDepartamento2(emp1.getEmpresaId());
         prc.setFk_departamentoId(dep.getDepartamentoId());

          if(prc==null){
              add(new wAviso("ERROR","ERROR INTERNO"));
          }
          if(dep==null){
              add(new wAviso("ERROR","ERROR INTERNO"));
          }
          if(emp1==null){
              add(new wAviso("ERROR","PRACTICANTE NO ENCONTRADO O CONVENIO NO EXISTE"));
          }
          else{
                  int res=dPracticante.SaveUpdate(prc);
                  Polizaseguro ps=new Polizaseguro(prc.getPracticanteId());
       ps=new Polizaseguro(prc.getPracticanteId(),ps.getFk_planseguroId());
       aig po=new aig();
       try{
           po.xmlEditar(ps);
       }
       catch(Exception exc){
           add(new wAviso("ERROR","NO SE PUDO CREAR LA POLIZA"));
       }
                  if(res!=0){
           add(new wAviso("EXITO","EL PRACTICANTE"+" "+prc.getNombre()+prc.getPracticanteId()+" "+"HA SIDO CAMBIADO A LA EMPRESA"+" "+emp1.getRazon_empresa()+""+"EXITOSAMENTE"));
       }
 else{
        add(new wAviso("ERROR","EL PRACTICANTE NO PUDO SER CAMBIADO"));
 }
      CleanFields();
      UpdateView();

          }

   ocultarFilas();
   UpdateView();
 }

    }

}
         
